package socketTest.chapter03;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class ToUpperTCPNIOClient2 {


    public String toUpperRemote(String serverIp, int serverPort, String str) {
        SocketChannel socketChannel = null;
        try {
            socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress(serverIp, serverPort));
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            socketChannel.write(ByteBuffer.wrap(str.getBytes()));
            StringBuilder stringBuilder = new StringBuilder();
            while (socketChannel.read(buffer) > 0) {
                buffer.flip();
                stringBuilder.append(new String(buffer.array()));
                buffer.clear();
            }
            socketChannel.close();
            return stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
            if (socketChannel != null && socketChannel.isConnected()) {
                try {
                    socketChannel.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return "";
    }

    public static void main(String[] args) {
        ToUpperTCPNIOClient2 client = new ToUpperTCPNIOClient2();
        String recvStr = client.toUpperRemote(ToUpperTCPNIOServer.SERVER_IP, ToUpperTCPNIOServer.SERVER_PORT, "aaaAAAbbbBBBcccCCC");
        System.out.println("收到:" + recvStr);
    }
}